package yl.hs.bmipfull.controllers.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.pojo.system.SysFileEntity;
import yl.hs.bmipfull.service.production.IProductShipOrderService;
import yl.hs.bmipfull.service.system.IFileService;
import yl.hs.bmipfull.viewmodels.WebResult;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author 张凯
 * @apiNote
 * @since 2022/1/20 8:56 上午 创建
 */
@RequestMapping("/api/file")
@Controller
@Api(value = "文件管理Web接口", tags = "系统管理——文件管理操作")
public class FileController extends ControllerBase {

    @Autowired
    IFileService fileService;
    @Value("${hsxx.file.url}")
    String fileUrl;

    /**
     * 实现文件上传
     */
    @RequestMapping("")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ResponseBody
    public WebResult fileUpload(@RequestParam("filename") MultipartFile file) {
        if (file.isEmpty()) {
            return fail("文件为空");
        }
        String fileName = file.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + fileUrl + System.currentTimeMillis() + "_" + fileName;
        File dest = new File(filePath);

        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(dest);
            SysFileEntity sysFile = new SysFileEntity();
            sysFile.setFileSize(file.getSize());
            sysFile.setFilePath(filePath);
            sysFile.setOriginalFileName(file.getOriginalFilename());
            String[] split = fileName.split("\\.");
            if (split.length > 0) {
                sysFile.setFileType(split[split.length - 1]);
            }

            return success("上传成功", fileService.save(sysFile));
        } catch (IllegalStateException | IOException e) {

            return error(e);
        }


    }

    @DeleteMapping("/{sn}")
    @ApiOperation(value = "删除文件", notes = "删除文件")
    public WebResult deleteFile(@PathVariable String sn) {
        fileService.delete(sn);
        return success("ok");
    }


    @GetMapping("/{sn}")
    @ApiOperation(value = "获取文件",notes = "获取文件")
    public void downloadFile(@PathVariable String sn, HttpServletResponse response) throws Exception {
        SysFileEntity sysFile = fileService.findBySn(sn);
        if (sysFile != null){
            File file = new File(sysFile.getFilePath());
            if (file.exists()){
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                // 设置文件名
                response.addHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));
                response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                byte[] buffer = new byte[1024];
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();

                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }

                }
                finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }


    }


    @GetMapping("/update")
    @ApiOperation(value = "更新文件",notes = "更新文件")
    public WebResult updateFiles(){
       var result = orderService.updateFiles();
       return success("已更新"+result+"个发货单");
    }

    private IProductShipOrderService orderService;

    @Autowired
    public void setOrderService(IProductShipOrderService orderService) {
        this.orderService = orderService;
    }
}
